package com.free.md5parser.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {

    private static final String KEY = "md5_123456789012";

    private static final String IV = KEY;

    /**
     * 加密数据
     */
    public static String aesEncode(String content) {
        try {
            // 获取加密对象
            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = content.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            // 指定秘钥规则：传入密钥的字节数组与指定的算法
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
            // 初始化加密对象: 指定加密模式与秘钥规则
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
            // 开始加密
            byte[] encrypted = cipher.doFinal(plaintext);

            // 对字节数字进行Base64编码
            String encode = new BASE64Encoder().encode(encrypted);
            // 数据过长Base64会自动添加换行符
            return encode.replaceAll(System.lineSeparator(), "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 解密数据
     */
    public static String aesDecode(String content) {
        try {
            byte[] decoded = new BASE64Decoder().decodeBuffer(content);
            // 获取Cipher对象
            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");
            // 指定秘钥规则：传入密钥的字节数组与指定的算法
            SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
            // 初始化解密对象: 指定解密模式与秘钥规则
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            // 解密
            byte[] original = cipher.doFinal(decoded);
            return new String(original).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}